﻿using JV.Com.Business;
using JV.Com.ViewModels;
using JV.Com.ViewModels.Wrapper;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;

namespace JV.Com.Internals
{
    public sealed class NewsItemDetailCollection : ObservableCollection<NewsWrapper>,
        ISupportIncrementalLoading
    {
        private int m_currentPage;

        private readonly int m_idToSelect;
        private readonly NewsListPageViewModel m_parent;

        public NewsItemDetailCollection(NewsListPageViewModel parent, int idToSelect)
        {
            m_parent = parent;
            m_idToSelect = idToSelect;
        }

        public bool HasMoreItems
        {
            get { return m_currentPage < 10; }
        }

        public Windows.Foundation.IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            var dispatcher = Window.Current.Dispatcher;
            return Task.Run<LoadMoreItemsResult>(async () =>
                {
                    var result = await Service.GetLatestNewsAsync(m_currentPage);
                    uint resultCount = 0;
                    if(result == null || result.Count() == 0)
                    {
                        m_currentPage = 10;
                    }
                    else
                    {
                        resultCount = (uint)result.Count();
                        await dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(async () =>
                            {
                                foreach(var news in result)
                                {
                                    var wrapper = new NewsWrapper(m_parent, news);
                                    this.Add(wrapper);
                                    if (m_idToSelect == news.Id)
                                    {
                                        await m_parent.SelectNewsByIdAsync(wrapper.Id);
                                    }
                                }
                            }));
                    }

                    m_currentPage++;
                    return new LoadMoreItemsResult() { Count = resultCount };
                }).AsAsyncOperation<LoadMoreItemsResult>();
        }
    }
}
